package com.alog.storage.net;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import com.alipay.sdk.app.PayTask;
import com.alog.storage.Contants;
import com.alog.storage.R;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.yintong.android.app.IPayService;
import com.yintong.android.app.IRemoteServiceCallback;
import com.yintong.secure.service.PayService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class PayRunnable implements Runnable {
    protected final int FAILURE = -1;
    protected final int SUCCESS = 0;
    protected final int PROCESS = 1;
    private Activity context;
    private BaseAPI.APICallback callback;
    private Object orderInfo;
    private boolean isRun;
    private int apiId;

    public PayRunnable(Activity context, int apiId, Object orderInfo, BaseAPI.APICallback callback) {
        this.context = context;
        this.isRun = true;
        this.apiId = apiId;
        this.orderInfo = orderInfo;
        this.callback = callback;
    }

    public void cancelRequest() {
        this.isRun = false;
    }

    @Override
    public void run() {
        if (apiId == Contants.API_ID_PAY_ALIPAY) {
            alipayPay();
        } else if (apiId == Contants.API_ID_PAY_WX) {
            wxPay();
        } else if (apiId == Contants.API_ID_PAY_UNIONPAY) {
            unionpayPay();
        }
    }

    private void alipayPay() {
        PayTask alipay = new PayTask(this.context);
        Map<String, String> result = alipay.payV2(orderInfo.toString(), true);
        if ("9000".equals(result.get("resultStatus"))) {
            callback(SUCCESS);
        } else {
            callback(FAILURE);
        }
    }

    private void wxPay() {
        PayReq req = new PayReq();
        HashMap<String, String> map = (HashMap<String, String>) orderInfo;
        req.appId = map.get("appid");
        req.partnerId = map.get("partnerid");
        req.prepayId = map.get("prepayid");
        req.nonceStr = map.get("noncestr");
        req.timeStamp = map.get("timestamp");
        req.packageValue = map.get("package");
        req.sign = map.get("sign");
        req.extData = "app data";
        IWXAPI wxApi = WXAPIFactory.createWXAPI(context, req.appId);
        wxApi.registerApp(req.appId);
        wxApi.sendReq(req);
        context = null;
        callback = null;
    }

    private void unionpayPay() {
        context.bindService(new Intent(context, PayService.class), unionpayConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection unionpayConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {
            try {
                IPayService payService = IPayService.Stub.asInterface(service);
                payService.registerCallback(unionpayCallback);
                String result = payService.pay(orderInfo.toString());
                payService.unregisterCallback(unionpayCallback);
                context.unbindService(unionpayConnection);
                unionpayResult(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
        }
    };

    private IRemoteServiceCallback unionpayCallback = new IRemoteServiceCallback.Stub() {
        public void startActivity(String packageName, String className, int iCallingPid, Bundle bundle) throws RemoteException {
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            if (bundle == null) bundle = new Bundle();
            try {
                bundle.putInt("CallingPid", iCallingPid);
                intent.putExtras(bundle);
            } catch (Exception e) {
                e.printStackTrace();
            }
            intent.setClassName(packageName, className);
            context.startActivity(intent);
        }

        @Override
        public boolean isHideLoadingScreen() throws RemoteException {
            return false;
        }

        @Override
        public void payEnd(boolean arg0, String arg1) throws RemoteException {
        }
    };

    private void unionpayResult(String result) {
        try {
            JSONObject objContent = new JSONObject(result);
            String retCode = objContent.optString("ret_code");
            if ("0000".equals(retCode)) {
                callback(SUCCESS);
            } else if ("2008".equals(retCode)) {
                callback(PROCESS);
            } else {
                callback(FAILURE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void callback(int what) {
        if (isRun) {
            Message msg = new Message();
            msg.what = what;
            mHandler.sendMessage(msg);
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FAILURE:
                    callback.onFailure(apiId, FAILURE, context.getString(R.string.pay_failure));
                    break;
                case SUCCESS:
                    callback.onSuccess(apiId, context.getString(R.string.pay_success));
                    break;
                case PROCESS:
                    callback.onFailure(apiId, PROCESS, context.getString(R.string.pay_process));
                    break;

            }
            context = null;
            callback = null;
        }
    };

}
